package com.sskj.mqtt.many;

import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Like
 * @Date: 2025/3/3 15:40
 * @Description: 封装处理程序
 */
public class HandlerWrapper {
    private final Object target;
    private final Method method;
    private final Class<?>[] parameterTypes;
    // 增加原始过滤表达式字段
    private final String originalFilter;

    public HandlerWrapper(Object target, Method method, String originalFilter) {
        this.target = target;
        this.method = method;
        this.originalFilter = originalFilter;
        this.parameterTypes = method.getParameterTypes();
        method.setAccessible(true);
    }

    public void invoke(String clientId, String topic, byte[] payload) throws Exception {
        Object[] args = buildArguments(clientId, topic, payload);
        method.invoke(target, args);
    }

    private Object[] buildArguments(String clientId, String topic, byte[] payload) {
        List<Object> args = new ArrayList<>();
        for (Class<?> paramType : parameterTypes) {
            if (paramType == String.class) {
                // 根据参数位置决定填充内容
                if (args.isEmpty()) {
                    args.add(clientId);
                } else if (args.size() == 1) {
                    args.add(topic);
                } else {
                    args.add(new String(payload));
                }
            } else if (paramType == byte[].class) {
                args.add(payload);
            } else if (paramType == MqttMessage.class) {
                MqttMessage message = new MqttMessage(payload);
                args.add(message);
            } else {
                String[] topicParts = topic.split("/");
                String[] filterParts = this.originalFilter.split("/");

                for (int i = 0; i < filterParts.length; i++) {
                    if (filterParts[i].equals("+") && i < topicParts.length) {
                        args.add(topicParts[i]);
                    }
                }

                // 确保参数数量匹配
                if (args.size() < parameterTypes.length) {
                    throw new IllegalArgumentException("参数数量不匹配");
                }
            }
        }
        return args.toArray();
    }

    private String getOriginalFilter() {
        return this.originalFilter; // 直接返回存储的表达式
    }
}
